package com.kll.carolinehmibiz.model

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kll.carolinehmibiz.base.utils.SpUtils
import com.kll.carolinehmibiz.net.bean.GetSystemMenuResponse


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/8 20:16
 * <a href="mailto:752577456@qq.com">Contact me</a>
 * ====================================================
 */
class SystemModel {

    private var systemMenus: ArrayList<GetSystemMenuResponse>? = null
    private var mContext: Context? = null

    companion object {

        private var mInstance: SystemModel? = null

        fun getInstance(context: Context): SystemModel{
            if(mInstance == null) {
                mInstance = SystemModel(context)
            }
            return mInstance!!
        }
    }

    constructor(context: Context) {
        mContext = context.applicationContext
    }

    /**
     * 获取菜单
     */
    fun getMenus(parentId: Int): ArrayList<GetSystemMenuResponse> {

        // 菜单为空时尝试从缓存中加载
        if(systemMenus == null || systemMenus!!.isEmpty()) {
            systemMenus = Gson().fromJson(SpUtils.getInstance().getValueByString(mContext, "SYSTEM_MENU"),
                object: TypeToken<ArrayList<GetSystemMenuResponse>>(){}.type)
        }

        if(systemMenus?.isNotEmpty() == true) {
            var menus = arrayListOf<GetSystemMenuResponse>()
            for(index in systemMenus!!.indices) {
                if(systemMenus!![index].parent_id == parentId) {
                    menus.add(systemMenus!![index])
                }
            }
            return menus
        }

        return arrayListOf()
    }

    /**
     * 保存菜单
     */
    fun saveMenu(menus: ArrayList<GetSystemMenuResponse>) {
        systemMenus = menus
        SpUtils.getInstance().saveValueToSharePerference(mContext, "SYSTEM_MENU", Gson().toJson(menus))
    }


}